﻿using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.CT_NBIoT;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.Extensions.Logging;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Atmk.WaterMeter.MIS.Logic.TempLogic
{
    public class OwnerDal
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly ICT_PlatformDevideManageLogic _ctPlatformDevideManageLogic;

        public OwnerDal()
        {
            
        }
        public OwnerDal(ICT_PlatformDevideManageLogic ctPlatformDevideManageLogic)
        {
            _ctPlatformDevideManageLogic = ctPlatformDevideManageLogic;
        }
        public bool Insert(string districtId, dynamic owner, dynamic meter, Token token, out string ErrorMessage)
        {
            if (meter.meterNumber.ToString().Trim() == "")
            {
                ErrorMessage = "请添写水表编号";
                _logger.Debug(ErrorMessage);
                return false;
            }

            var longitude = 0.00;
            var latitude = 0.00;
            var elevation = 0.00;
            try
            {
                longitude = Convert.ToDouble(owner.longitude); //Simple.DoubleConvertString(owner.longitude.ToString());
                latitude = Convert.ToDouble(owner.latitude);
                elevation = Convert.ToDouble(owner.elevation);
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message.ToString();
                return false;
            }
            try
            {
                using (var context = new atmk_wmdb_devContext())
                {
                    //判断 是否新建业主，ownerId 为空则新建业主
                    string ownerId = owner.ownerId.ToString();
                    Owner ownerEntity = null;
                    if (string.IsNullOrWhiteSpace(ownerId))
                    {
                        //接收业主实体
                        ownerEntity = new Owner()
                        {
                            DistrictId = districtId,
                            HouseNumber = owner.houseNumber.ToString().Trim(),
                            Mobile = owner.mobile.ToString().Trim(),
                            Memo = owner.ownerMessage.ToString()
                        };
                        _logger.Debug("水表添加1："+GenericsJsonConvert.JsonSerialize(ownerEntity));
                        //如果手机号存在 就返回false
                        if (context.Owner.Any(m => m.Mobile == ownerEntity.Mobile && !string.IsNullOrWhiteSpace(ownerEntity.Mobile)))
                        {
                            ErrorMessage = "手机号已存在！";
                            return false;
                        }
                        context.Owner.Add(ownerEntity);
                        //添加业主坐标
    //                    _mapRepository.Edit(ownerEntity.Id.ToString(), CoordinateType.Owner, longitude, latitude,
    //elevation);
                        //context.SaveChanges();

                    }
                    //接收水表实体
                    var meterEntity = new Meter()
                    {
                        OwnerId = ownerEntity == null ? ownerId : ownerEntity.Id.ToString(),
                        MeterNumber = meter.meterNumber.ToString().Trim(),
                        MeterState = Enum.GetName(typeof(MeterDocumentState), MeterDocumentState.建档),
                        CommType = meter.commType,
                        MeterType = meter.meterType.ToString(),
                        RefillType = meter.refillType.ToString(),
                        PrcieStepId = meter.priceId.ToString(),
                        Memo = meter.meterDatas.ToString()
                    };
                    _logger.Debug("水表添加2：" + GenericsJsonConvert.JsonSerialize(meterEntity));
                    if (string.IsNullOrEmpty(meterEntity.CommType))
                        meterEntity.CommType = "CT_NB";
                    //新增水表
                    _logger.Debug("水表添加3：");
                    if (context.MeterCodeIdMap.Any(m => m.Number == meterEntity.MeterNumber) || context.Meter.Any(m => m.MeterNumber == meterEntity.MeterNumber))
                    {
                        ErrorMessage = "表号已存在";
                        return false;
                    }
                    string imei = GenericsJsonConvert.ObjectJsonParament("collector", meterEntity.Memo);
                    _logger.Debug("水表添加4：" + imei);
                    if (context.MeterCodeIdMap.Any(m => m.Imei == imei))
                    {
                        GenericsJsonConvert.ObjectJsonParament("collector", meter.Memo);
                        ErrorMessage = "采集器IMEI号已存在";
                        return false;
                    }
                    context.Meter.Add(meterEntity);
                    //context.SaveChanges();
                    //向电信平台注册设备 返回电信设备唯一标识
                    //string mapId = CreatNBEntityTOCTNB(meterEntity, imei);
                    //if (LogicModule.IsDevPhase)
                    //    return Guid.NewGuid().ToString("N");
                    //前置 获取水表IMEI(memo-collector)号

                    #region 向电信平台注册设备
                    var res = _ctPlatformDevideManageLogic.AddDevice(imei, "WaterMeter", meterEntity.MeterNumber);

                    var result = res.Result;
                    _logger.Debug("水表添加5：" + result);
                    if (!result.Success)
                        throw new NotImplementedException($"平台创建新设备失败{result.ErrorMessage}");
                    string mapId = result.Message;
                    #endregion

                    var meterCodeIdMap = new MeterCodeIdMap
                    {
                        Number = meterEntity.MeterNumber,
                        CtNbId = mapId,
                        Imei = imei,
                        ProjectId = token.payload.areaid,
                        DistrictId = districtId,
                        MeterId = meterEntity.Id.ToString(),
                        OwerId = meterEntity.OwnerId
                    };
                    _logger.Debug("水表添加6：" + GenericsJsonConvert.JsonSerialize(meterCodeIdMap));
                    context.MeterCodeIdMap.Add(meterCodeIdMap);
                    var result_count = context.SaveChanges();
                    ErrorMessage = "添加成功";
                    return result_count>0;

                }
            }
            catch (Exception e)
            {
                _logger.Debug("水表添加7：" + e.Message);
                _logger.Error(e);
                ErrorMessage = e.Message.ToString();
                return false;
            }
        }

        //查询方法 后期提取
        public object Select(int type, string areaId, string aid, string nodeType, int page, int pageSize, int count,
    int meterState, string searchType = "", string searchValue = "")
        {
            try
            {
                //获取所有叶子片区信息--临时
                using (var context = new atmk_wmdb_devContext())
                {
                    List<District> total_districts;
                    List<Owner> total_owners = null;
                    List<Meter> total_meters = null;

                    if (nodeType == "leaf")
                    {
                        total_districts = context.District.Where(m => m.Id.ToString() == aid).ToList();
                        total_owners = context.Owner.Where(m => m.Id.ToString() == aid).ToList();
                        total_meters = context.Meter.Where(m => m.OwnerId == aid && m.MeterState != "销户").OrderByDescending(m => m.CreateTime).ToList();
                        total_districts = context.District.Where(m => m.Id.ToString() == total_owners.First().DistrictId).ToList();
                    }
                    else
                    {
                        var Projects2district = context.District.Where(m => m.ProjectId == areaId).ToList();
                        total_districts = Tools.getNodeNext(Projects2district, aid, Projects2district, new List<District>());
                        var districts_ids = total_districts.Select(m1 => m1.Id.ToString());
                        total_owners = context.Owner.Where(o => districts_ids.Contains(o.DistrictId)).ToList();
                        var owners_ids = total_owners.Select(m1 => m1.Id.ToString());
                        total_meters = context.Meter.Where(m => owners_ids.Contains(m.OwnerId) && m.MeterState != "销户").OrderByDescending(m => m.CreateTime).ToList();
                    }

                    //项目水费列表
                    var PrcieSteps = context.PrcieStep.Where(m => m.ProjectId.ToString() == areaId).ToList();
                    if (meterState > 0)
                    {
                        var meterEnumName = Enum.GetName(typeof(MeterDocumentState), meterState - 1);
                        total_meters = total_meters.Where(m => m.MeterState == meterEnumName).ToList();
                    }

                    //meter = _baseInfoLogic.QuerySearchMeter(searchType, searchValue, total_meters);
                    //拼接
                    //var file = Combination(type, total_districts, total_owners, total_meters, PrcieSteps);
                    //count = file.Count;

                    //获取分页数据
                    //var pageList = PaginatedList<object>.Create(file.ToList(), page, pageSize);
                    //return pageList;
                    return new object();
                }
            }
            catch (Exception e)
            {
                _logger.Error("业主档案Select方法报错信息：" + e.ToString());
                throw new Exception(e.ToString(), e);
            }
        }
    }
}
